<?php

/**
 * ownCloud - user_joomla
 *
 * @author pipapai.com
 * @copyright 2013 pipapai.com
 *
 */

/**
 * Class for user management hooks 
 */
class OC_USER_JOOMLA_Hooks {
   /**
    * @brief Create a new user
    * @param $email The email of the user to create
    * @param $password The password of the new user
    * @returns true/false
    *
    * Creates a new user. Basic checking of username is done in OC_User
    * itself, not in its subclasses.
    */
   public static function createUser( $parameters ) {
      $master = PFactory::getMasterUser();

      /* update masteraccount */
      $db = PFactory::getDbo(); 
      $query = 'INSERT INTO `*PREFIX*user_ownership` (`uid`, `owner` ) VALUES( ' . 
               $db->quote($parameters['uid']) . ', ' . 
               $db->quote($master->id) . ')'; 
      $db->setQuery(PUtil::replaceOCPrefix($query)); 
      $db->execute(); 
      return true;
   }

   /**
    * @brief delete a user
    * @param $email The username of the user to delete
    * @returns true/false
    *
    * Deletes a user
    */
   public static function deleteUser( $parameters ) {
      $master = PFactory::getMasterUser();
      // Remote it from user_ownership table 
      $db = PFactory::getDbo(); 
      $query = 'DELETE FROM `*PREFIX*user_ownership` WHERE `uid`= ' . $db->quote($parameters['uid']) . ' AND `owner` = ' . $db->quote($master->id); 

      $db->setQuery(PUtil::replaceOCPrefix($query)); 
      $db->execute(); 
      return true;
   }
   

   /**
    * @brief update lastvisitDate
    * @param $email The username of the user to update lastvisitDate
    * @returns true/false
    *
    * update lastvisitDate
    */
   public static function logout( $parameters ) {
      $user= PFactory::getUser();

      // not guest, update last visit 
      if(!$user->get("guest")) {
         if($user->get("id") > 0)
            $user->setLastVisit();
         else 
            PCompanyHelper::setSubUserLastLogonDate($user->get("username"));
      }

      // destory all sessions for main user or subaccount 
      // avoid $session->destroy to prevent warnings 
      $session = PFactory::getSession();
      if (isset($_COOKIE[session_name()])) {
         $config = PFactory::getConfig();
         $cookie_domain = $config->get('cookie_domain', '');
         $cookie_path = $config->get('cookie_path', '/');
         setcookie(session_name(), '', time() - 42000, $cookie_path, $cookie_domain);
      }

      // Force logout all users with that userid ? 
      $db = PFactory::getDbo();
      $db->setQuery(
         'DELETE FROM '.$db->quoteName('#__session') .
        ' WHERE '.$db->quoteName('session_id').' = '.$db->quote($session->getId())
      );
      $db->execute();
      return true;
   }

}
